package com.ruoyi.common.utils.baidu;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class TransApi {

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "20200528000473659";
    private static final String SECURITY_KEY = "yszhyADPDPZyXraft5j_";

    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private String appid;
    private String securityKey;

    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        //params.put("dict", "0");
        //params.put("tts", "0");

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    public static JSONObject trans(String query) throws InterruptedException {
        Thread.sleep(100);
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String result = api.getTransResult(query, "auto", "auto");
        if(StringUtils.contains(result, "error_code")) {
            System.out.println(result);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        System.out.println(jsonObject);
        if(jsonObject.containsKey("trans_result")) {
            JSONObject res = (JSONObject) jsonObject.getJSONArray("trans_result").get(0);
            if(res != null) {
                String dictStr = res.getString("dict");
                if(StringUtils.isNotBlank(dictStr)) {
                    JSONObject dict = JSON.parseObject(dictStr);
                    // System.out.println(JSON.toJSONString(dict));
                    res.put("dict", dict);
                }
            }
        }
        return jsonObject;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(trans("could"));
    }

}
